import {_decorator, Collider, Component, ICollisionEvent} from 'cc';
import {PropViewModel} from "db://assets/Scripts/MVC/Prop/PropViewModel";
import {PropUiState} from "db://assets/Scripts/MVC/Prop/PropUiState";
import {CollisionGroup} from "db://assets/Scripts/Common/CollisionGroup";
import {EventManager} from "db://assets/Scripts/Common/EventManager";
import {EventType} from "db://assets/Scripts/Common/EventType";

const {ccclass, property} = _decorator;

/**
 * 道具Controller
 */
@ccclass('PropController')
export class PropController extends Component {
    /**
     * 道具ViewModel
     */
    public viewModel: PropViewModel = new PropViewModel();
    /**
     * 道具UiState
     */
    public uiState: PropUiState = this.viewModel.uiState;

    onLoad() {
        // 初始化碰撞器
        this.uiState.collider = this.getComponent(Collider);
    }

    onEnable() {
        // 碰撞检测
        this.uiState.collider.on('onCollisionEnter', this.onCollisionEnter, this);
    }

    onDisable() {
        // 移除碰撞检测
        this.uiState.collider.off('onCollisionEnter', this.onCollisionEnter, this);
    }

    start() {

    }

    update(deltaTime: number) {
        // 移动
        this.move(deltaTime);
        // 改变X方向
        this.changeDirX();
        // 检测是否超过最大范围
        this.checkOutRange();
    }

    /**
     * 移动
     */
    private move(deltaTime: number) {
        // 获取位置
        const position = this.node.position;
        // 设置位置
        this.node.setPosition(position.x + this.uiState.dirX * this.uiState.speed * deltaTime,
            position.y, position.z + this.uiState.speed * deltaTime);
    }

    /**
     * 改变 X 方向
     */
    private changeDirX() {
        // 获取位置
        const position = this.node.position;
        if (position.x < this.uiState.leftRange) {
            this.uiState.dirX = 1;
        }
        if (position.x > this.uiState.rightRange) {
            this.uiState.dirX = -1;
        }
    }

    /**
     * 检测是否超过最大范围
     */
    private checkOutRange() {
        // 当越过最大位置阈值时
        if (this.node.position.z > this.uiState.outRange) {
            // 销毁
            this.node.destroy();
        }
    }

    /**
     * 碰撞检测
     *
     * @param event 碰撞事件
     */
    private onCollisionEnter(event: ICollisionEvent) {
        // 另一个碰撞器的分组
        const otherGroup = event.otherCollider.getGroup();
        // 与玩家发生碰撞
        if (otherGroup === CollisionGroup.PLAYER_PLANE) {
            // 销毁
            this.node.destroy();
            // 切换子弹
            EventManager.emit(EventType.UPDATE_BULLET, this.viewModel.getBulletType(this.node.name));
        }
    }
}